<template>
  <div>
    <div class="msg">
      <a-row type="flex" class="msg-bhead">
        <a-col :span="2" v-if="shop.type == 'shop'">发布商品</a-col>
        <a-col :span="2" v-if="shop.type == 'edit'">编辑商品</a-col>
      </a-row>
      <a-form
        :form="form"
        class="forms"
        labelAlign="left"
        :labelCol="{span:3}"
        :wrapperCol="{span:8}"
      >
        <a-form-item label="游戏名称">{{this.shop.list_name}}</a-form-item>
        <a-form-item label="商品类型">{{this.shop.cate_name}}</a-form-item>
        <a-form-item label="商品标题">
          <a-input
            placeholder="这里输入商品标题"
            v-decorator="['title', { rules: [{ required: true, message: '请输入商品标题！' }] }]"
          />
        </a-form-item>
        <a-form-item label="操作系统">
          <a-select
            placeholder="未选择"
            v-decorator="['system', { rules: [{ required: true, message: '请选择操作系统！' }] }]"
          >
            <a-select-option value="0">pc</a-select-option>
            <a-select-option value="1">苹果</a-select-option>
            <a-select-option value="2">安卓</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="区服">
          <a-cascader
            :fieldNames="{ label: 'name', value: 'wow_de_id', children: 'two' }"
            :options="options"
            placeholder="未选择"
            @change="handleChanges"
            v-decorator="['wow_id', {
               rules: [{ required: true, message: '请选择区服！' }] }]"
          />
        </a-form-item>
        <!-- <a-form-item label="装备类型">
          <a-select
            placeholder="未选择"
            v-decorator="['two_cate_id', { rules: [{ required: true, message: '请选择装备类型！' }] }]"
          >
            <a-select-option
              :value="item.cate_id"
              v-for="(item,index) in twocateArr"
              :key="index"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>-->

        <a-form-item label="商品价格">
          <a-input-number
            id="inputNumber"
            :min="1"
            :precision="2"
            placeholder="这里输入价格，最低20"
            v-decorator="['price', { rules: [{ required: true, message: '请输入商品价格！' }] }]"
            style="width:388px;"
          />
        </a-form-item>
        <a-form-item label="上传商品封面" :wrapperCol="{span:20}">
          <a-upload
            name="icon"
            listType="picture-card"
            :showUploadList="false"
            :customRequest="customRequest"
            @change="handleChange"
          >
            <img v-if="icon" :src="icon" alt="icon" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="上传商品图片" :wrapperCol="{span:20}">
          <a-upload
            name="image"
            listType="picture-card"
            :fileList="fileList"
            @preview="handlePreview"
            :customRequest="customRequest"
            :remove="removes"
            @change="handleChange"
          >
            <div v-if="fileList.length < 11">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <div class="lines"></div>

        <a-form-item :label="item" v-for="(item,index) in infoArr" :key="index">
          <a-input
            :placeholder="'这里输入' + item"
            v-decorator="[item, { rules: [{ required: true, message: `请输入${item}！` }] }]"
          />
        </a-form-item>
      </a-form>
    </div>
    <div class="box-b">
      <a-button @click="previous">{{shop.type == 'shop'?'重新选择游戏':'返回'}}</a-button>
      <a-button type="primary" @click="submit">发布</a-button>
    </div>
  </div>
</template>

<script>
var qiniu = require("qiniu-js");
import {
  GAT_WOW,
  GAT_CATE,
  PUBLISH_SHOP,
  BASETO_QINIU,
  UP_TOKEN,
  GET_PARAMETER,
  SAVE_SHOP
} from "./server";
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  props: {
    shop: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: "shopmsg" }),
      wow_id: "",
      previewVisible: false,
      previewImage: "",
      options: [],
      icon: "",
      fileList: [],
      twocateArr: [],
      qnToken: "",
      loading: false,
      infoArr: []
    };
  },
  created() {
    this.getWow();
    this.getCate();
    this.getToken();
    this.getParameter();
  },
  methods: {
    handleChanges(e) {},
    submit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.$store.state.member_id) {
            this.$store.commit("loginSoft", true);
            return;
          }
          if (!this.icon) {
            this.$message.error("上传商品封面！");
            return;
          }
          if (this.fileList.length <= 0) {
            this.$message.error("上传商品图片！");
            return;
          }
          let imgArr = [];
          this.fileList.forEach((ele, i) => {
            imgArr.push(ele.url);
          });
          let getInfo = this.form.getFieldsValue();
          let info = [];
          for (let k of this.infoArr) {
            info.push({ [k]: getInfo[k] });
          }
          let json = {
            list_id: this.shop.list_id,
            cate_id: this.shop.cate_id,
            image: imgArr.join(","),
            icon: this.icon,
            // two_cate_id: this.form.getFieldValue("two_cate_id"),
            title: this.form.getFieldValue("title"),
            price: this.form.getFieldValue("price"),
            info: JSON.stringify(info),
            system: this.form.getFieldValue("system"),
            wow_id: this.form.getFieldValue("wow_id")[
              this.form.getFieldValue("wow_id").length - 1
            ]
          };
          if (this.shop.type == "shop") {
            PUBLISH_SHOP(json).then(res => {
              if (!res) return;
              this.$router.push({ name: "mine-release" });
            });
          } else {
            SAVE_SHOP({ game_id: this.shop.game_id, ...json }).then(res => {
              if (!res) return;
              this.$emit("previous");
            });
          }
        }
      });
    },
    previous() {
      this.$emit("previous");
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    customRequest(file) {
      this.loading = true;
      this.inputUpload(file.file, file.filename);
    },
    inputUpload(e, n) {
      let that = this;
      let random1 = parseInt(Math.random() * 100000);
      let random2 = parseInt(Math.random() * 100000);
      let time = new Date().getTime();
      let d = e.name.lastIndexOf(".");
      let hz = e.name.substring(d);
      let fileName = "" + random1 + random2 + time + hz;
      let observable = qiniu.upload(e, fileName, this.qnToken);
      observable.subscribe({
        next() {},
        error() {
          that.$message.error("上传失败！");
        },
        complete(res) {
          that.loading = false;
          if (n == "icon") {
            that.icon = "https://oss.itemplay.com/" + res.key;
          } else {
            that.fileList.push({
              uid: res.key,
              name: res.key,
              status: "done",
              url: "https://oss.itemplay.com/" + res.key
            });
          }
        }
      });
    },
    handleChange() {},
    removes(file) {
      this.fileList.forEach((ele, i) => {
        if (ele.status == file.status) this.fileList.splice(i, 1);
      });
      return true;
    },
    getWow() {
      GAT_WOW({
        list_id: this.shop.list_id
      }).then(res => {
        if (!res) return;
        this.options = res.data;
      });
    },
    getCate() {
      GAT_CATE({
        list_id: this.shop.list_id,
        lv: 0
      }).then(res => {
        if (!res) return;
        this.twocateArr = res.data;
      });
    },
    getToken() {
      UP_TOKEN().then(res => {
        if (!res) return;
        this.qnToken = res.data;
      });
    },
    getParameter() {
      GET_PARAMETER({
        list_id: this.shop.list_id,
        cate_id: this.shop.cate_id
      }).then(res => {
        if (!res) return;
        this.infoArr = res.data;
        if (this.shop.type == "edit") {
          this.$nextTick(() => {
            let shop = this.shop;
            shop.info = JSON.parse(shop.info);
            this.icon = shop.icon;
            shop.image = shop.image.split(",");
            shop.image.forEach(ele => {
              this.fileList.push({
                uid: ele,
                name: ele,
                status: "done",
                url: ele
              });
            });
            let infoJson = {
              system: shop.system,
              wow_id: [shop.one, shop.wow_de_id],
              title: shop.title,
              price: shop.price
              // two_cate_id: shop.two_cate_id
            };
            shop.info.forEach(ele => {
              let k = Object.keys(ele)[0];
              infoJson[k] = ele[k];
            });
            this.form.setFieldsValue(infoJson);
          });
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.msg {
  border: 1px solid #e8e8e8;
  padding: 18px;
  .msg-bhead {
    height: 36px;
    line-height: 36px;
    text-align: center;
    background: #f6f6f6;
    border-bottom: 1px solid #e8e8e8;
    margin: -18px -18px 4px -18px;
    font-weight: bold;
  }
  .information {
    margin-top: 20px;
    padding-bottom: 20px;
    border-bottom: 1px dashed #e8e8e8;
    img {
      width: 80px;
      height: 80px;
    }
    .information-n {
      margin-bottom: 14px;
      font-size: 18px;
    }
    .information-q {
      font-size: 12px;
      color: #999;
    }
  }
  .forms {
    margin-top: 24px;
    // input {
    //   width: 400px;
    // }
    // &/deep/.ant-select-selection {
    //   width: 400px;
    // }
    .y {
      color: #337ab7;
      div:last-child {
        text-align: right;
      }
    }
    .lines {
      border: 1px dashed #e8e8e8;
      margin: 40px 0;
    }
    .all-price {
      height: 38px;
    }
    .new-price {
      height: 36px;
      span {
        color: #0084ff;
        font-size: 16px;
      }
    }
    .btn {
      width: 160px;
      height: 42px;
      color: #fff;
      background: #0084ff;
      border: 0;
      margin-right: 14px;
      margin-top: 20px;
    }
  }
}
.box-b {
  height: 80px;
  line-height: 80px;
  text-align: center;
  background: #e8e8e8;
  button {
    width: 170px;
  }
}
</style>